package com.sub.framework.rabbitmq.message;

import com.google.protobuf.InvalidProtocolBufferException;
import com.sub.common.proto.DataProto;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.lang.reflect.Type;
import java.nio.ByteBuffer;

/**
 * TODO
 *
 * @author AZHE_SUN
 * @date 2020-8-20 18:18
 **/
public class ProtoMessageConverter implements MessageConverter {
    /**
     * object转换为ProtoBuf, 发送消息
     */
//    @Override
//    public Message createMessage(Object object, MessageProperties messageProperties) {
//        System.out.println("发送转换的消息");
//        DataProto.Content person = (DataProto.Content)object;
//        return new Message(person.toByteArray(), messageProperties);
//    }

    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        DataProto.Content person = (DataProto.Content)o;
       byte[] msgs = ByteBuffer.wrap(person.toByteArray(), 0, person.toByteArray().length).array();
        messageProperties.setContentType("application/octet-stream");
        messageProperties.setContentEncoding("UTF-8");
        return new Message(msgs, messageProperties);
    }


    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        System.out.println("转换消息");
//        String contentType =   message.getMessageProperties().getContentType();
        DataProto.Content  from = null;
        try {
            from = DataProto.Content.parseFrom( message.getBody() );
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        return from;
    }


}
